package com.vxb.testmvp.test_retrofit;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.google.gson.Gson;
import com.vxb.testmvp.R;
import com.vxb.testmvp.test_retrofit.entity.Entity;
import com.vxb.testmvp.test_retrofit.entity.LoginBase;
import com.vxb.testmvp.util.SPUtils;
import com.vxb.testmvp.util.Util;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.OkHttpClient;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.http.GET;
import retrofit2.http.POST;
import retrofit2.http.Query;
import rx.Observable;
import rx.Subscriber;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class TestRetrofitActivity extends AppCompatActivity {

    private APi mApi;
    private TextView tv1, tv2, tv_token;
    private Button bt_login;
    private EditText et_pwd, et_user, et_qiyehao;

    private LoginAPIService mLoginService;
    private LoginAPIService2 mLoginService2;


    public interface LoginAPIService {
        /**
         * 登录
         */
        @POST("login")
        Call<LoginBase> login(@Query("userMobile") String mobile, @Query("userPassword") String password,
                              @Query("companyId") String companyId);


    }

    public interface LoginAPIService2 {
        /**
         * 登录
         */
        @POST("login")
        Observable<LoginBase> login2(@Query("userMobile") String mobile, @Query("userPassword") String password,
                                     @Query("companyId") String companyId);

    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_test_retrofit);


        tv1 = (TextView) findViewById(R.id.tv_text1);
        tv2 = (TextView) findViewById(R.id.tv_text2);
        tv_token = (TextView) findViewById(R.id.tv_token);

        bt_login = (Button) findViewById(R.id.bt_login);

        et_pwd = (EditText) findViewById(R.id.et_pwd);
        et_user = (EditText) findViewById(R.id.et_user);
        et_qiyehao = (EditText) findViewById(R.id.et_qiyehao);

        bt_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //login();
                login2();
            }
        });


        RequestQueue mQueue = Volley.newRequestQueue(this);
        final StringRequest request = new StringRequest(Request.Method.GET, "http://apis.juhe.cn/mobile/get?phone=18622320104&dtype=&key=16b78ba328a9e5485a68c83b8844e904",
                new ResponseSuccessListener(), new ResponseFailListener());

        mQueue.add(request);
        Test();


    }

    private void login() {

        Retrofit loginRetrofit = new Retrofit.Builder()
                //使用自定义的mGsonConverterFactory
                .addConverterFactory(GsonConverterFactory.create())
                .baseUrl("http://192.168.0.240:8080/mpm_operate/v2/")
                .build();

        mLoginService = loginRetrofit.create(LoginAPIService.class);

        final Call<LoginBase> loginb = mLoginService.login(et_user.getText().toString(), et_pwd.getText().toString(), et_qiyehao.getText().toString());

        loginb.enqueue(new Callback<LoginBase>() {
            @Override
            public void onResponse(Call<LoginBase> call, Response<LoginBase> response) {
                LoginBase loginBase = response.body();
                String token = loginBase.loginData.token;

                SPUtils.put("token", token, TestRetrofitActivity.this);
                Util.showToast(TestRetrofitActivity.this, "token = " + token);
                tv_token.setText(TestRetrofitActivity.this.getString(R.string.token, token));

                launch(RetrofitMainActivity.class);

            }

            @Override
            public void onFailure(Call<LoginBase> call, Throwable t) {
                t.printStackTrace();
            }
        });

    }

    private void login2() {

        Retrofit loginRetrofit = new Retrofit.Builder()
                //使用自定义的mGsonConverterFactory
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .baseUrl("http://192.168.0.240:8080/mpm_operate/v2/")
                .build();

        mLoginService2 = loginRetrofit.create(LoginAPIService2.class);


        Observable<LoginBase> observerable = mLoginService2.login2(et_user.getText().toString(), et_pwd.getText().toString(), et_qiyehao.getText().toString());

        observerable
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<LoginBase>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onNext(LoginBase loginBase) {
                        String token = loginBase.loginData.token;

                        SPUtils.put("token", token, TestRetrofitActivity.this);
                        Util.showToast(TestRetrofitActivity.this, "token = " + token);
                        tv_token.setText(TestRetrofitActivity.this.getString(R.string.token, token));

                        launch(RetrofitMainActivity.class);
                    }
                });

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    protected void launch(Class<?> cls) {
        Intent intent = new Intent(this, cls);
        startActivity(intent);
    }


    private class ResponseSuccessListener implements com.android.volley.Response.Listener<String> {

        @Override
        public void onResponse(String response) {
            tv1.setText(response);
            Gson gson = new Gson();
            Entity entity = gson.fromJson(response, Entity.class);
            tv1.append(entity.getResultcode() + "fff");
        }
    }

    private class ResponseFailListener implements com.android.volley.Response.ErrorListener {

        @Override
        public void onErrorResponse(VolleyError error) {
            Toast.makeText(TestRetrofitActivity.this, error.toString(), Toast.LENGTH_SHORT).show();
        }
    }


    private void Test() {
        //http://apis.juhe.cn/mobile/get?phone=18622320104&dtype=&key=16b78ba328a9e5485a68c83b8844e904
        //创建retrofit对象
        Retrofit retrofit = new Retrofit.Builder()
                //使用自定义的mGsonConverterFactory
                .addConverterFactory(GsonConverterFactory.create())
                .baseUrl("http://apis.juhe.cn/mobile/")
                .build();
        // 实例化我们的mApi对象
        mApi = retrofit.create(APi.class);

        // 调用我们的响应的方法
        Call<Entity> ss = mApi.getNews("18622320104", "", "16b78ba328a9e5485a68c83b8844e904");

        ss.enqueue(new Callback<Entity>() {
            @Override
            public void onResponse(Call<Entity> call, Response<Entity> response) {

                Entity news = response.body();
                tv2.append(news.toString());

                Log.i("body", response.toString());
            }

            @Override
            public void onFailure(Call<Entity> call, Throwable t) {
                Log.i("body", "body");
                t.printStackTrace();
            }
        });
    }


    public interface APi {
        @GET("get")
        Call<Entity> getNews(@Query("phone") String phone, @Query("dtype") String dtype, @Query("key") String key);
    }


}
